# 必要的库
import cv2
import datetime

# 调用本地摄像头，本次实例用的是笔记本电脑摄像头，一般默认是0。
cap = cv2.VideoCapture(0)
# 如果是使用录像的话请进行以下操作：
# filepath = "此处输入需要读取的视频文件路径"
# cap = cv2.VideoCapture(filepath)

# 加载预训练的人脸检测模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

before = None
count = 1
time = datetime.date.today()
print("移动物体识别开始！")
print(str(datetime.datetime.now()))

# 获取图像
while True:
    ret, frame = cap.read()

    # 结束时退出循环
    if ret == False:
        break

    # 转成灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    if before is None:
        before = gray.astype("float")
        continue

    # 计算当前画面与移动平均线的差分
    cv2.accumulateWeighted(gray, before, 0.5)
    frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(before))
    # 将差分图二值化
    thresh = cv2.threshold(frameDelta, 3, 255, cv2.THRESH_BINARY)[1]
    # 提取轮廓
    contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
    # 描点，框选
    for target in contours:
        x, y, w, h = cv2.boundingRect(target)

        # 改变需要侦测的物体大小，可根据需求进行调整
        if w < 100:
            continue
        areaframe = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)


    # 进行人脸检测
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    # 在检测到的每张脸上画框
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

    # 显示结果图像
    cv2.imshow('Face Detection', frame)
    # ESC键退出程序
    if cv2.waitKey(1) == 27: break

print("移动物体识别结束。")
print(str(datetime.datetime.now()))

# 关闭窗口
cv2.destroyAllWindows()
